<template>
  <div class="car-list">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input
            v-model="searchForm.fname"
            placeholder="请输入航线名称"
            clearable
            @keyup.enter.native="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 航班列表 -->
    <el-card v-loading="loading">
      <el-row :gutter="20" class="car-grid">
        <el-col 
          v-for="car in carList" 
          :key="car.cid" 
          :xs="24" 
          :sm="12" 
          :md="8" 
          :lg="6"
        >
          <el-card :body-style="{ padding: '0px' }" class="car-card">
            <div class="car-image">
              <el-image
                :src="getImageUrl(car.fimg)"
                fit="cover"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </div>
            
            <div class="car-info">
              <h3 class="car-name">{{ car.fname }}</h3>
              <h4 class="car-name">{{ car.ffrom }}---{{ car.fto }}</h4>

              <div class="car-desc">{{ car.finfo }}</div>
              <div class="car-price">
                <span class="price">¥{{ car.frent }}</span>
              </div>
              
              <div class="car-actions">
                <el-button 
                  type="primary" 
                  size="small"
                  @click="handleRent(car)"
                >
                  {{ '购票'}}
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <el-empty v-if="!loading && carList.length === 0" description="暂无航班信息"></el-empty>
    </el-card>

    <!-- 对话框 -->
    <el-dialog
      title="确认订票信息"
      :visible.sync="rentDialog.visible"
      width="500px"
      custom-class="ticket-dialog"
    >
      <div class="ticket-form">
        <!-- 航班信息展示 -->
        <div class="flight-info">
          <div class="route-info">
            <div class="city-info">
              <span class="city from">{{ rentDialog.car?.ffrom }}</span>
              <span class="arrow">
                <i class="el-icon-right"></i>
              </span>
              <span class="city to">{{ rentDialog.car?.fto }}</span>
            </div>
            <div class="flight-name">{{ rentDialog.car?.fname }}</div>
          </div>
          
          <div class="price-info">
            <span class="label">票价</span>
            <span class="price">¥{{ rentDialog.car?.frent }}</span>
          </div>
        </div>

        <!-- 乘客信息表单 -->
        <el-form 
          :model="rentDialog.form" 
          :rules="rentDialog.rules"
          ref="rentForm"
          label-width="100px"
          class="passenger-form"
        >

          <!-- <el-form-item label="身份证号" prop="idCard">
            <el-input 
              v-model="rentDialog.form.idCard"
              placeholder="请输入身份证号"
            ></el-input>
          </el-form-item> -->

          <el-form-item label="支付方式" prop="payType">
            <el-radio-group v-model="rentDialog.form.payType">
              <el-radio :label=1 checked>
                <i class="el-icon-money payment-icon wechat"></i>
                微信支付
              </el-radio>
              <el-radio :label=0>
                <i class="el-icon-money payment-icon alipay"></i>
                支付宝
              </el-radio>
            </el-radio-group>
          </el-form-item>

        </el-form>

        <!-- 提示信息 -->
        <div class="notice-section">
          <el-alert
            title="请仔细核对订票信息，提交后不可修改"
            type="warning"
            :closable="false"
            show-icon
          >
          </el-alert>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="rentDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRent" :loading="rentDialog.loading">
          确认购票
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'FlightList',
  
  data() {
    return {
      searchForm: {
        fname: ''
      },
      carList: [],
      loading: false,
      rentDialog: {
        visible: false,
        loading: false,
        car: null,
        form: {
          passengerName: '',
          idCard: '',
          payType: 1,
        },
        rules: {
          passengerName: [
            { required: true, message: '请输入乘客姓名', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
          ],
          idCard: [
            { required: true, message: '请输入身份证号', trigger: 'blur' },
            { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
          ],
          payType: [
            { required: true, message: '请选择支付方式', trigger: 'blur' }
          ]
        }
      },
      dateOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      }
    }
  },

  created() {
    this.fetchData()
  },

  methods: {
    // 获取航班列表
    async fetchData() {
      this.loading = true
      try {
        const res = await request.get('/FlightSearchServlet', {
          params: {
            cname: this.searchForm.fname || ''
          }
        })
        
        console.log('API响应:', res) // 调试日志
        
        if (res.code === 0) {
          if (Array.isArray(res.data)) {
            this.carList = res.data.filter(item => (item.fStatus === 1 || item.fStatus === 0))
            console.log('航班列表:', this.carList) // 调试日志
          } else {
            console.error('返回的数据不是数组:', res.data)
            this.carList = []
          }
        } else {
          this.$message.error(res.msg || '获取航班列表失败')
        }
      } catch (error) {
        console.error('获取航班列表失败:', error)
        this.$message.error('获取航班列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.fetchData()
    },

    // 购票
    handleRent(car) {
      this.rentDialog.car = car
      this.rentDialog.visible = true
    },

    // 确认购票
    async confirmRent() {
      if (!this.rentDialog.car) return
      
      try {
        await this.$refs.rentForm.validate()
        
        const email = localStorage.getItem('email')
        if (!email) {
          this.$message.warning('请先登录')
          this.$router.push('/login')
          return
        }

        this.rentDialog.loading = true
        
        const orderRes = await request.get('/PutOrderServlet', {
          params: {
            fid: this.rentDialog.car.fid,
            frent: this.rentDialog.car.frent,
            email: email,
            fname: this.rentDialog.car.fname,
            idCard: this.rentDialog.form.idCard,
            paytype: this.rentDialog.form.payType
            
          }
        })
        
        if (orderRes.code === 0) {
          this.$message({
            type: 'success',
            message: '订单创建成功，正在跳转支付...',
            duration: 1500
          })
          
          setTimeout(() => {
            this.$message.success('支付成功')
            this.rentDialog.visible = false
            this.fetchData()
          }, 1500)
        } else {
          this.$message.error(orderRes.msg || '订票失败')
        }
      } catch (error) {
        console.error('订票失败:', error)
        this.$message.error('订票失败')
      } finally {
        this.rentDialog.loading = false
      }
    },

    // 修改图片URL处理方法
    getImageUrl(cimg) {
      if (!cimg) {
        return require('@/assets/images/car-default.jpg')
      }
            
      // 拼接完整路径
      return `http://localhost:8080/exam_war/${cimg}`
    }
  }
}
</script>

<style lang="less" scoped>
.car-list {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f0f2f5;

  .search-card {
    margin-bottom: 20px;
  }

  .car-grid {
    display: flex;
    flex-wrap: wrap;
    margin: -10px;
  }

  .car-card {
    flex: 1;
    min-width: 280px;
    margin: 10px;
    transition: all 0.3s;
    background-color: #fff;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    }

    .car-image {
      height: 200px;
      overflow: hidden;
      background-color: #f5f7fa;

      .el-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        color: #909399;
        font-size: 30px;
      }
    }

    .car-info {
      padding: 14px;

      .car-name {
        margin: 0;
        font-size: 16px;
        color: #303133;
        font-weight: bold;
      }

      .car-desc {
        margin: 8px 0;
        font-size: 14px;
        color: #909399;
        height: 40px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .car-price {
        margin: 8px 0;
        
        .price {
          font-size: 20px;
          color: #f56c6c;
          font-weight: bold;
        }
        
        .unit {
          font-size: 14px;
          color: #909399;
          margin-left: 4px;
        }
      }

      .car-actions {
        margin-top: 12px;
        text-align: right;
      }
    }
  }

  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }
}

.ticket-dialog {
  .ticket-form {
    padding: 20px;

    .flight-info {
      background: #f8f9fa;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 24px;

      .route-info {
        margin-bottom: 16px;

        .city-info {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 8px;

          .city {
            font-size: 24px;
            font-weight: bold;
            color: #1a365d;
          }

          .arrow {
            margin: 0 20px;
            color: #409EFF;
            
            i {
              font-size: 20px;
            }
          }
        }

        .flight-name {
          text-align: center;
          color: #666;
          font-size: 14px;
        }
      }

      .price-info {
        text-align: center;
        
        .label {
          color: #666;
          margin-right: 8px;
        }

        .price {
          color: #f56c6c;
          font-size: 20px;
          font-weight: bold;
        }
      }
    }

    .passenger-form {
      margin-bottom: 24px;

      .payment-icon {
        margin-right: 8px;
        font-size: 18px;
      }

      .el-radio {
        margin-right: 20px;
        margin-bottom: 10px;
        
        &:hover {
          color: #409EFF;
        }
      }

      .wechat {
        color: #07c160;
      }

      .alipay {
        color: #1677ff;
      }

      .unionpay {
        color: #e93b3d;
      }
    }

    .notice-section {
      margin-top: 20px;
    }
  }
}

.dialog-footer {
  text-align: center;
  padding-top: 10px;
}

// 添加支付方式的响应式布局
@media screen and (max-width: 768px) {
  .el-radio-group {
    display: flex;
    flex-direction: column;
    
    .el-radio {
      margin-bottom: 12px;
    }
  }
}
</style> 